package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author L5775
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    //private Long[] ids;

    @Override
    public void save(Employee employee, Long[] ids) {
        //this.ids = ids;
        //检查参数合法性
        //假设业务很复杂
        employeeMapper.insert(employee);

        //关联关系,把数据插入到中间表
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }
    }

    @Override
    public void delete(Long id) {
        //删除关系
        employeeMapper.deleteRelation(id);

        employeeMapper.deleteByPrimaryKey(id);

    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除关系
        employeeMapper.deleteRelation(employee.getId());
        //关联关系,把数据插入到中间表
        if (ids != null && ids.length > 0) {
            for (long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageResult<Employee> query(QueryObject qo) {
        int count = employeeMapper.selectForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), count, Collections.emptyList());
        }
        //判断当前页是否大于总页数
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize()
                : count / qo.getPageSize() + 1;
        if (qo.getCurrentPage()>totalPage){
            //如果大于就设置当前页为最后一页
            qo.setCurrentPage(totalPage);
        }

        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), count, employees);
    }

    @Override
    public Employee login(String username, String password) {
        if (username == null || username.equals("")) {
            throw new RuntimeException("用户名不能为空");
        }
        if (password == null || password.equals("")) {
            throw new RuntimeException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username,password);
        if (employee==null){
            throw new  RuntimeException("用户名或密码错误");
        }
        return employee;
    }
}
